package cn.wusifx.zabbix;

import cn.wusifx.zabbix.request.BaseRequest;
import cn.wusifx.zabbix.request.RequestHandler;
import cn.wusifx.zabbix.request.builder.AuthRequestBuilder;
import cn.wusifx.zabbix.request.builder.UnAuthRequestBuilder;
import cn.wusifx.zabbix.request.builder.apiinfo.ApiinfoRequestBuilder;
import cn.wusifx.zabbix.response.*;
import cn.wusifx.zabbix.response.apiinfo.ApiinfoGetResponse;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonEncoder;
import feign.slf4j.Slf4jLogger;

import java.time.Instant;

public class Zabbix {
    private static Api api = null;
    private String url = "api_jsonrpc.php";
    private String auth;
    public void init(String host){
        init(host,Logger.Level.FULL);
    }
    public void init(String host, Logger.Level level){
        api = Feign.builder()
                .logger(new Slf4jLogger()).logLevel(level)
                .requestInterceptor(new RequestHandler())
                .decoder(new ResponseDecoder())
                .encoder(new GsonEncoder())
                .target(Api.class,host);
        BaseResponse<String> baseResponse = this.call(new ApiinfoRequestBuilder().builder());
        System.out.printf("client version:%s->server version:%s",Version.info,new ApiinfoGetResponse(baseResponse).getVersion());
        System.out.println();
    }
    public void init(String host,String url,Logger.Level level){
        this.url = url;
        this.init(host,level);
    }
    public void init(String host,String url){
        this.url = url;
        this.init(host);
    }

    public String getAuth() {
        return auth;
    }

    public <T> BaseResponse<T> call(BaseRequest baseRequest){
        return api.jsonrpc(baseRequest,url);
    }

    public String auth(String userName,String password){
        BaseResponse<String> baseResponse = this.call(new AuthRequestBuilder(Instant.now().getEpochSecond()).setUserName(userName).setPassword(password).builder());
        auth = baseResponse.getResult();
        return baseResponse.getResult();
    }
    public Boolean unAuth(String auth){
        BaseResponse<Boolean> baseResponse = this.call(new UnAuthRequestBuilder(Instant.now().getEpochSecond(),auth).builder());
        return baseResponse.getResult();
    }
    public Boolean unAuth(){
        return this.unAuth(auth);
    }
}
